package com.lijinjiang.constraints;

import com.lijinjiang.model.DateModel;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @Description 该类提供了一个简单的约束，将可选日期限制在给定范围内
 * @Author lijinjiang
 * @Date 2024-12-30 10:52
 */
public class RangeConstraint implements DateSelectionConstraint {

    /**
     * 可选日期的下界
     */
    private LocalDateTime start;

    /**
     * 可选日期的上界
     */
    private LocalDateTime end;

    /**
     * 为给定日期之间（和不包括）的值创建一个新的约束
     * @param start 值的下界，不包括
     * @param end   值的上界，不包括
     */
    public RangeConstraint(LocalDateTime start, LocalDateTime end) {
        this.start = start;
        this.end = end;
        cleanTime();
    }

    /**
     * 为给定日期之间（和不包括）的值创建一个新的约束
     * @param start 值的下界，不包括
     * @param end   值的上界，不包括
     */
    public RangeConstraint(LocalDate start, LocalDate end) {
        this.start = start.atStartOfDay();
        this.end = end.atStartOfDay();
        cleanTime();
    }

    /**
     * 清除时间尾数
     */
    private void cleanTime() {
        if (start != null) {
            start = start.withHour(0);
            start = start.withMinute(0);
            start = start.withSecond(0);
            start = start.withNano(0);
        }

        if (end != null) {
            end = end.withHour(23);
            end = end.withMinute(59);
            end = end.withSecond(59);
            end = end.withNano(999);
        }
    }

    public boolean isValidSelection(DateModel<?> model) {
        LocalDateTime dateTime = LocalDateTime.of(model.getYear(), model.getMonth(), model.getDay(), model.getHour(), model.getMinute(), model.getSecond());
        if (start != null && dateTime.isBefore(start)) {
            return false;

        }
        return end == null || !dateTime.isAfter(end);
    }
}
